package com.zhang.goods.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhang.common.model.SkuEsModel;
import com.zhang.common.dto.SkuSearchDto;
import com.zhang.common.util.redis.RedisUtil;
import com.zhang.goods.dto.SkuInfoDto;
import com.zhang.goods.entity.SkuImags;
import com.zhang.goods.entity.SkuInfo;
import com.zhang.common.model.SkuRecommendModel;
import com.zhang.goods.entity.SpuInfo;
import com.zhang.goods.mapper.SkuInfoMapper;
import com.zhang.goods.service.ISkuImagsService;
import com.zhang.goods.service.ISkuInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhang.goods.vo.ConfirmOrderSkuVo;
import com.zhang.goods.vo.SkuSearchResultVO;
import com.zhang.search.service.IProductElasticSearchService;
import com.zhang.system.service.IAdminUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * sku信息表 服务实现类
 * </p>
 *
 * @author 创世神
 * @since 2023-10-04
 */
@Service
@Slf4j
public class SkuInfoServiceImpl extends ServiceImpl<SkuInfoMapper, SkuInfo> implements ISkuInfoService {
    @Autowired
    private IAdminUserService adminUserService;
    @Autowired
    private ISkuImagsService skuImagesService;
    @Autowired
    private IProductElasticSearchService IProductElasticSearchService;
    @Autowired
    private RedisUtil redisUtil;

    private String preferencesPrefix = "Preferences";

    @Override
    public IPage getSkuListPage(SkuSearchDto skuSearchDto) {
        /*管管理员可以查看所有Sku信息
         * 非管理员只能查看自己的sku信息
         * 由于sku表并没有商家的字段，而spu有，需要查出商家的所有spu，然后查出所有spu下的sku*/
        Long adminId = StpUtil.getLoginIdAsLong();
        List<SpuInfo> spuInfoList = null;
        boolean isAdmin = adminUserService.isAdmin(adminId);
        if (!isAdmin) {
            skuSearchDto.setBusinessId(adminId.toString());
        }
        log.info("ceshi{}", skuSearchDto);
        return baseMapper.getSkuListPage(new Page<SkuInfo>(skuSearchDto.getPageNum(), skuSearchDto.getPageSize()), skuSearchDto);
    }

    @Override
    public void modifySku(SkuInfoDto skuInfoDto) {
        SkuInfo skuInfo = new SkuInfo();
        BeanUtils.copyProperties(skuInfoDto, skuInfo);
        if (skuInfoDto.getSkuDefaultImg() != null) {
            /*如果这个sku已经存在默认图片，那么需要将之前的默认图片修改为普通，然后再插入*/
            QueryWrapper<SkuImags> defaImgWarp = new QueryWrapper<>();
            defaImgWarp.eq("sku_id", skuInfoDto.getId())
                    .eq("is_default", 0);
            SkuImags defaImg = skuImagesService.getOne(defaImgWarp);
            if (defaImg != null) {
                defaImg.setIsDefault(1);
                skuImagesService.updateById(defaImg);
            }
            /*如果之前没有存在默认图片，那么直接插入一个默认图片的记录*/
            SkuImags imags = new SkuImags();
            imags.setSkuId(skuInfoDto.getId());
            imags.setImgId(skuInfoDto.getSkuDefaultImg());
            imags.setIsDefault(0);
            /*如果选用的默认图片已经存在，只需要更新他为默认图片就行，如果这个选用的默认图片是新建的，就需要插入
             * 借助saveOrUpdate的UpdateWrapper判断是否存在这个记录，存在就更新否则就插入*/
            UpdateWrapper<SkuImags> wrapper = new UpdateWrapper<SkuImags>();
            wrapper.eq("sku_id", skuInfoDto.getId())
                    .eq("img_id", skuInfoDto.getSkuDefaultImg());
            skuImagesService.saveOrUpdate(imags, wrapper);
        }
        List<Long> skuImgs = skuInfoDto.getSkuImgs();
        if (skuImgs.size() > 0) {
            for (Long skuImg : skuImgs) {
                SkuImags imags = new SkuImags();
                imags.setSkuId(skuInfoDto.getId());
                imags.setImgId(skuImg);
                imags.setIsDefault(1);//不默认
                skuImagesService.save(imags);
            }
        }
        try {
            updateById(skuInfo);
        } catch (Exception e) {
            log.error("sql更新实体是空的");
        }

    }

    @Override
    public List<SkuInfo> listBySpuId(Long spuId) {
        QueryWrapper<SkuInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("spu_id", spuId);
        return list(wrapper);

    }


    @Override
    public List<ConfirmOrderSkuVo> getOrderConfirmSkuInfo(List<Long> skuIds) {
        return baseMapper.getOrderConfirmSkuInfo(skuIds);
    }

    @Override
    public IPage getNewSkuList(IPage<SkuInfo> page) {
        return baseMapper.getNewSkuList(page);
    }

    @Override
    public SkuSearchResultVO getSkuListFromES(SkuSearchDto skuSearchDto) throws IOException {
        List<SkuEsModel> skuFromES = IProductElasticSearchService.getSkuFromES(skuSearchDto);
//        保存浏览记录
        if (StpUtil.isLogin()) {
            SkuRecommendModel skuRecommendModel = new SkuRecommendModel();
            if (skuSearchDto.getSearchValue() != null) {
                ArrayList<String> strings = new ArrayList<>();
                strings.add(skuSearchDto.getSearchValue());
                skuRecommendModel.setSearchWord(strings);
            }
            if (skuSearchDto.getBrandIds() != null) {
                skuRecommendModel.setBrandIds(skuSearchDto.getBrandIds());
            }
            if (skuSearchDto.getCategoryIds() != null) {
                skuRecommendModel.setCategoryIds(skuSearchDto.getCategoryIds());
            }
            savePreferences(skuRecommendModel);//保存用户的喜好模型
        }
        SkuSearchResultVO skuSearchResultVO = new SkuSearchResultVO(skuFromES);
//        处理分页数据
        skuSearchResultVO.setTotal(skuFromES.size());
        /*向上取整*/
        int pages = skuFromES.size() / skuSearchDto.getPageSize() + (skuFromES.size() % skuSearchDto.getPageSize() != 0 ? 1 : 0);
        skuSearchResultVO.setPages(pages);
        return skuSearchResultVO;
    }

    @Override
    public List<SkuEsModel> getSkuListByAdvice(int pageNum, int pageSize) {
//         用户推荐列表商品
//       如果是新用户，就按照综合
        SkuRecommendModel preferences;
        if (StpUtil.isLogin()) {
            preferences = getPreferences(StpUtil.getLoginIdAsString());
        }
        List<SkuEsModel> skuFromES = null;
        try {
//            skuFromES = IProductElasticSearchService.getSkuListByAdvice(preferences);
            SkuSearchDto skuSearchDto = new SkuSearchDto();
            skuSearchDto.setPageNum(pageNum);
            skuSearchDto.setPageSize(pageSize);
            skuFromES = IProductElasticSearchService.getSkuFromES(skuSearchDto);
        } catch (IOException e) {
            log.error("此处有异常:", e);
        }
        return skuFromES;
    }

    private List<SkuEsModel> getSkuListByAdviceFromDB(int pageNum, int pageSize) {
//        List<SkuEsModel> list=baseMapper.getUpSkuModelList(pageNum, pageSize);
        return null;
    }

    @Override
    public void savePreferences(SkuRecommendModel skuRecommendModel) {
        SkuRecommendModel preferences = getPreferences(StpUtil.getLoginIdAsString());
        String s = null;
        if (preferences == null) {
//            如果为空，就直接保存数据
            s = JSON.toJSONString(skuRecommendModel);
        } else {
//            如果已经有记录，需要将以前的记录继续添加
            if (skuRecommendModel.getCategoryIds() != null) {
                List<Long> categoryId = new ArrayList<>();
                if (preferences.getCategoryIds() != null) {
                    categoryId = preferences.getCategoryIds();
                }
                categoryId.addAll(skuRecommendModel.getCategoryIds());
                preferences.setCategoryIds(categoryId);
            }
            if (skuRecommendModel.getBrandIds() != null) {
                List<Long> brandIds = new ArrayList<>();
                if (preferences.getBrandIds() != null) {
                    brandIds = preferences.getBrandIds();
                }
                brandIds.addAll(skuRecommendModel.getBrandIds());
                preferences.setBrandIds(brandIds);
            }
            if (skuRecommendModel.getSearchWord() != null) {
                List<String> searchWord = new ArrayList<>();
                if (preferences.getSearchWord() != null) {
                    searchWord = preferences.getSearchWord();
                }
                searchWord.addAll(skuRecommendModel.getSearchWord());
                preferences.setSearchWord(searchWord);
            }
            s = JSON.toJSONString(preferences);
        }
        redisUtil.set(preferencesPrefix + StpUtil.getLoginIdAsString(), s);
    }

    @Override
    public void saleSku(Long skuId, Integer skuQuantity) {
        baseMapper.saleSku(skuId, skuQuantity);
    }

    @Override
    public List<SkuInfo> getStoreOtherSku(String skuId) {
        return baseMapper.getStoreOtherSku(skuId);
    }

    /**
     * 获取一个用户的喜好/浏览记录
     *
     * @param userId 用户id
     * @return {@link SkuRecommendModel}
     */
    private SkuRecommendModel getPreferences(String userId) {
        String toString = redisUtil.getToString(preferencesPrefix + userId);
        return JSON.parseObject(toString, SkuRecommendModel.class);
    }

}
